package com.jsmtr.rms.controller;

import cn.hutool.core.util.IdcardUtil;
import com.jsmtr.rms.entity.*;
import com.jsmtr.rms.service.*;
import com.jsmtr.rms.utils.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Table;
import org.apache.poi.hwpf.usermodel.TableIterator;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Controller
@RequestMapping("/talentpool")
public class LibTalentPoolController {

    @Resource
    private IUtilService utilService;
    @Resource
    private ILibTalentService libTalentService;
    @Resource
    private IDoResumeService doResumeService;
    @Resource
    private IProjectService projectService;
    @Resource
    private IResumeService resumeService;

    @Resource
    private IMemberService memberService;

    //[start] 人才库信息列表
    @RequestMapping("/index")
    public String Index(HttpServletRequest request, Model model) {
        try {
            //性别
            model.addAttribute("xb", utilService.optionList("A", "0"));
            //名族
            model.addAttribute("minzu", utilService.optionList("B", "0"));
            //婚否
            model.addAttribute("hk", utilService.optionList("C", "0"));
            //婚否
            model.addAttribute("hunfou", utilService.optionList("D", "0"));
            //政治面貌
            model.addAttribute("zzmm", utilService.optionList("E", "0"));
            //最高学历
            model.addAttribute("education", utilService.optionList("F", "0"));
            //专业技术职务类型
            model.addAttribute("posttype", utilService.optionList("I", "0"));
            //职业资格证
            model.addAttribute("jndj", utilService.optionList("O", "0"));

            model.addAttribute("fpath", utilService.getConfig("path"));

            //取消人才库选择根据菜单进入对应的人才库
            //人才库
            List<LibTalentType> types = libTalentService.geTalentTypes();
            StringBuilder str = new StringBuilder();
            for (LibTalentType type : types) {
                str.append("<option value='" + type.getId() + "'>" + type.getName() + "</option>");
            }
            model.addAttribute("rck", str);

            List years = projectService.getProjectInfoYears();
            if (years != null && years.size() > 0) {
                StringBuilder addyears = new StringBuilder();
                for (Object year : years) {
                    addyears.append("<option value='" + year + "'>" + year + "</option>");
                }
                model.addAttribute("addYears", addyears.toString());
                String lastYear = years.get(0).toString();
                List<ProjectInfo> projects = projectService.getProjectByYear(lastYear);
                if (projects != null && projects.size() > 0) {
                    StringBuilder pros = new StringBuilder();
                    for (ProjectInfo project : projects) {
                        if (project.getState() != EnumTools.ProjectState.编辑中.ordinal()) {
                            pros.append("<option value='" + project.getId() + "' hrtype='" + project.getRecruittype() + "'>" + project.getPname() + "</option>");
                        }
                    }
                    model.addAttribute("projects", pros.toString());
                }
            }

            //改为初始查询最近一年的方案
          /*  List<ProjectInfo> projects = projectService.getProjectInfos(-1);
            StringBuilder pros = new StringBuilder();
            for (ProjectInfo project : projects) {
                if(project.getState() != EnumTools.ProjectState.编辑中.ordinal()){
                    pros.append("<option value='" + project.getId() + "' hrtype='" + project.getRecruittype() + "'>" + project.getPname() + "</option>");
                }

            }
            model.addAttribute("projects", pros.toString());*/

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/Library/talentpool/index";
    }

    //简历筛选-查询简历数据
    @SuppressWarnings("unchecked")
    @RequestMapping("/getresumes")
    public void getresumes(HttpServletRequest request, HttpServletResponse response, UserResume resume) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));

            Map<String, Object> _map = new HashMap<String, Object>();
            _map.put("agefrom", request.getParameter("agefrom").trim());
            _map.put("ageto", request.getParameter("ageto").trim());
            _map.put("workyearfrom", request.getParameter("workyearfrom").trim());
            _map.put("workyearto", request.getParameter("workyearto").trim());
            _map.put("heightfrom", request.getParameter("heightfrom").trim());
            _map.put("heightto", request.getParameter("heightto").trim());

            Map<String, Object> map = libTalentService.getResumesMap(page, perpage, _map, resume);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");
            if (pageCount != 0) {
               /* Object object = map.get("list");
                int num = 1;
                for (UserResume dur : (List<UserResume>) object) {
                    result.append("<tr><td><input type=\"checkbox\" id=\"cb_" + dur.getId() + "\" /></td>");
                    result.append("<td>" + ((page - 1) * perpage + num) + "</td>");
                    result.append("<td class='link'><a target='_blank' href='" + request.getContextPath() + "/UserResume/ViewResume?cardno=" + dur.getCardno() + "'>" + dur.getName() + "</a></td>");
                    result.append("<td>" + dur.getSexname() + "</td>");
                    result.append("<td>" + dur.getMname() + "</td>");
                    result.append("<td>" + dur.getZzmmname() + "</td>");
                    result.append("<td>" + dur.getCardno() + "</td>");
                    result.append("<td>" + dur.getUniversity() + "</td>");
                    result.append("<td>" + dur.getMajorname() + "</td>");
                    result.append("<td>" + dur.getEducationname() + "</td>");
                    result.append("<td>" + dur.getTel() + "</td>");
                    result.append("<td>" + StringTools.nullToStr(dur.getLibname()) + "</td></tr>");
                    num++;
                }*/
                int num = 1;
                List<HashMap> object = (List<HashMap>) map.get("list");
                for (HashMap<String, Object> dur : object) {
                    result.append("<tr><td><input type=\"checkbox\" id=\"cb_" + dur.get("ID") + "\" /></td>");
                    result.append("<td>" + ((page - 1) * perpage + num) + "</td>");
                    //投简历总次数
                    Integer cardcount = Integer.parseInt(dur.get("CARDCOUNT").toString());
                    if (cardcount > 1) {
                        result.append("<td class='link'><a target='_blank' href='" + request.getContextPath() + "/UserResume/ViewResumeCardno?cardno=" + dur.get("CARDNO") + "'>" + dur.get("NAME") + "</a>&nbsp;<span class='layui-badge'>" + dur.get("CARDCOUNT") + "</span></td>");
                    } else {
                        result.append("<td class='link'><a target='_blank' href='" + request.getContextPath() + "/UserResume/ViewResumeCardno?cardno=" + dur.get("CARDNO") + "'>" + dur.get("NAME") + "</a></td>");
                    }

                    result.append("<td>" + dur.get("SEXNAME") + "</td>");
                    result.append("<td>" + dur.get("MNAME") + "</td>");
                    result.append("<td>" + dur.get("ZZMMNAME") + "</td>");
                    result.append("<td>" + dur.get("CARDNO") + "</td>");
                    result.append("<td>" + dur.get("UNIVERSITY") + "</td>");
                    result.append("<td>" + dur.get("MAJORNAME") + "</td>");
                    result.append("<td>" + dur.get("EDUCATIONNAME") + "</td>");
                    result.append("<td>" + dur.get("TEL") + "</td>");
                    result.append("<td>" + StringTools.nullToStr(dur.get("LIBNAME")) + "</td></tr>");
                    num++;
                }
            } else {
                result.append("<tr><td colspan='12'>无符合条件的信息</td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='12'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }

    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping("/getresumesJson")
    public LayuiDataTableResultBean getresumesJson(HttpServletRequest request, HttpServletResponse response, UserResume resume) {
        LayuiDataTableResultBean result = new LayuiDataTableResultBean();
        try {
            int limit = Integer.parseInt(request.getParameter("limit"));
            int page = Integer.parseInt(request.getParameter("page"));

            Map<String, Object> _map = new HashMap<String, Object>();
            _map.put("agefrom", request.getParameter("agefrom").trim());
            _map.put("ageto", request.getParameter("ageto").trim());
            _map.put("workyearfrom", request.getParameter("workyearfrom").trim());
            _map.put("workyearto", request.getParameter("workyearto").trim());
            _map.put("heightfrom", request.getParameter("heightfrom").trim());
            _map.put("heightto", request.getParameter("heightto").trim());

            Map<String, Object> map = libTalentService.getResumesMap(page, limit, _map, resume);
            List<HashMap> list = (List<HashMap>) map.get("list");
            JSONArray data = new JSONArray();
            for (HashMap<String, Object> dur :
                    list) {
                JSONObject item = new JSONObject();
                item.put("ID", dur.get("ID"));
                item.put("CARDCOUNT", Integer.parseInt(dur.get("CARDCOUNT").toString()));
                item.put("SEXNAME", dur.get("SEXNAME"));
                item.put("MNAME", dur.get("MNAME"));
                item.put("ZZMMNAME", dur.get("ZZMMNAME"));
                item.put("CARDNO", dur.get("CARDNO"));
                item.put("NAME", dur.get("NAME"));
                item.put("UNIVERSITY", dur.get("UNIVERSITY"));
                item.put("MAJORNAME", dur.get("MAJORNAME"));
                item.put("EDUCATIONNAME", dur.get("EDUCATIONNAME"));
                item.put("TEL", dur.get("TEL"));
                int resume_type = ((BigDecimal) dur.get("RESUME_TYPE")).intValue();
                String resumeType = "";
                if (resume_type == EnumTools.RecruitType.不限.ordinal()) {
                    resumeType = "不限";
                } else if (resume_type == EnumTools.RecruitType.高校校园招聘.ordinal()) {
                    resumeType = "高校校园招聘";
                } else if (resume_type == EnumTools.RecruitType.中专校园招聘.ordinal()) {
                    resumeType = "中专校园招聘";
                } else if (resume_type == EnumTools.RecruitType.社会招聘.ordinal()) {
                    resumeType = "社会招聘";
                } else if (resume_type == EnumTools.RecruitType.内部招聘.ordinal()) {
                    resumeType = "内部招聘";
                } else if (resume_type == EnumTools.RecruitType.驾驶员招聘.ordinal()) {
                    resumeType = "驾驶员招聘";
                }
                item.put("RESUME_TYPE", resumeType);
                data.add(item);
            }

            result.setCount(0);
            result.setMsg("success");
            result.setCount(((Double) map.get("count")).intValue());
            result.setData(data);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }


    //[end]


    //[start] 添加人才库分类
    @RequestMapping(value = "/AddTypeAction")
    public void AddTypeAction(HttpServletRequest request, HttpServletResponse response, LibTalentType type) {
        try {
            LibTalentType _type = libTalentService.geTalentType(type.getName());
            if (_type == null) {
                type.setId(UUID.randomUUID().toString());
                utilService.addObject(type);
                utilService.printJsonResult(true, "操作成功！", "no", response);
            } else {
                utilService.printJsonResult(false, "该人才库已存在！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }
    //[end]

    //[start] 获得人才库分类列表
    @RequestMapping(value = "/gettalents", method = RequestMethod.GET)
    public void gettalents(HttpServletRequest request, HttpServletResponse response) {
        try {
            final List<LibTalentType> libTalentTypes = libTalentService.geTalentTypes();
            List<LibTalentType> types = libTalentTypes;
            StringBuilder str = new StringBuilder();
            int num = 1;
            for (LibTalentType type : types) {
                str.append("<tr><td>" + num + "</td>");
                str.append("<td>" + type.getName() + "</td>");
                str.append("<td>" + type.getRemark() + "</td>");
                str.append("<td class='link'><a href='javascript:' rel='" + type.getId() + "'>删除</a></td></tr>");
                num++;
            }
            utilService.printTextResult(str.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("", response);
        }
    }

    //[end]

    //[start] 删除人才库
    @RequestMapping(value = "/DelTalentAction", method = RequestMethod.POST)
    public void DelTalentAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id").trim();
            List<UserResume> resumes = libTalentService.getLibResume(id);
            for (UserResume resume : resumes) {
                resume.setLibid(null);
                resume.setLibname(null);
            }
            utilService.delList(libTalentService.geTalentType(id, 0), resumes);
            utilService.printJsonResult(true, "操作成功！", "no", response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }
    //[end]

    //[start] 添加到人才储备库
    @RequestMapping(value = "/SendToAction", method = RequestMethod.POST)
    public void SendToAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String tid = request.getParameter("tid").trim();
            LibTalentType type = libTalentService.geTalentType(tid, 0);
            if (type != null) {
                String[] ids = request.getParameterValues("id");
                List<UserResume> resumes = libTalentService.getResumes(ids);
                for (UserResume resume : resumes) {
                    resume.setLibid(type.getId());
                    resume.setLibname(type.getName());
                }
                utilService.editList(resumes);
                utilService.printJsonResult(true, "操作成功！", "no", response);
            } else {
                utilService.printJsonResult(false, "人才储备库不存在", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }
    //[end]

    //[start] 转出简历库
    @RequestMapping(value = "/RemoveAction", method = RequestMethod.POST)
    public void RemoveAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String[] ids = request.getParameterValues("id");
            List<UserResume> resumes = libTalentService.getResumes(ids);
            for (UserResume resume : resumes) {
                resume.setLibid(null);
                resume.setLibname(null);
            }
            utilService.editList(resumes);
            utilService.printJsonResult(true, "操作成功！", "no", response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }
    //[end]

    //[start] 获得招聘岗位
    @RequestMapping("/getposition")
    public void getPositionByPro(HttpServletRequest request, HttpServletResponse response) {
        try {
            String proid = request.getParameter("proid").trim();
            ProjectInfo proInfo = projectService.getpProjectById(proid);
            //if (proInfo.getRecruittype() != EnumTools.RecruitType.社会招聘.ordinal()) {
            //     utilService.printTextResult("非法访问", response);
            // } else {
            List<ProjectInfoJobs> jobs = projectService.getjobsbypid(proid);
            StringBuilder dstr = new StringBuilder();
            for (ProjectInfoJobs job : jobs) {
                dstr.append("<option value='" + job.getId() + "'>" + job.getJobname() + "</option>");
            }
            utilService.printTextResult(dstr.toString(), response);
            //}
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("", response);
        }
    }
    //[end]

    //[start] 获得招聘地区
    @RequestMapping("/getregion")
    public void getRegion(HttpServletRequest request, HttpServletResponse response) {
        try {
            String proid = request.getParameter("proid").trim();
            ProjectInfo proInfo = projectService.getpProjectById(proid);
            // if (proInfo.getRecruittype() != EnumTools.RecruitType.高校校园招聘.ordinal()) {
            //      utilService.printTextResult("非法访问", response);
            // } else {
            List<ProjectInfoRegion> regions = projectService.getRegionbypid(proid);
            StringBuilder dstr = new StringBuilder();
            for (ProjectInfoRegion region : regions) {
                dstr.append("<option value='" + region.getRcode() + "'>" + region.getRegion() + "</option>");
            }
            utilService.printTextResult(dstr.toString(), response);
            //  }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("", response);
        }
    }
    //[end]

    //[start] 将人才简历投递到招聘方案
    @RequestMapping(value = "/AddToPro", method = RequestMethod.POST)
    public void AddToPro(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id").trim();
            String pid = request.getParameter("pid").trim();
            ProjectInfo project = projectService.getpProjectById(pid);
            if (project.getRecruittype() == EnumTools.RecruitType.社会招聘.ordinal()) {
                String jid = request.getParameter("jid").trim(); // PlanPersondemand实体主键
                SendResumeSZ(project, jid, id, response);

            } else if (project.getRecruittype() == EnumTools.RecruitType.内部招聘.ordinal()) {
                String jid = request.getParameter("jid").trim();
                SendResumeSZ(project, jid, id, response);
            } else if (project.getRecruittype() == EnumTools.RecruitType.中专校园招聘.ordinal()) {
                if (project.getSeason().equalsIgnoreCase("春季")) {
                    String jid = request.getParameter("jid").trim();
                    SendResumeSZ(project, jid, id, response);
                } else {
                    SendResumeZZ(project, id, response);
                }

            } else if (project.getRecruittype() == EnumTools.RecruitType.高校校园招聘.ordinal()) {
                String jid = request.getParameter("jid"); // PlanPersondemand实体主键
                if (StringTools.trimNotEmpty(jid) && !jid.toString().equalsIgnoreCase("null")) {
                    SendResumeSZ(project, jid, id, response);
                    //SendResumeGX(project, rcode, region, id, response);
                } else {
                    SendResumeGX(project, null, null, id, response);
                }
            } else if (project.getRecruittype() == EnumTools.RecruitType.驾驶员招聘.ordinal()) {
                String jid = request.getParameter("jid").trim();
                SendResumeSZ(project, jid, id, response);
            } else {
                utilService.printJsonResult(false, "非法访问！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    public void AddToProBak(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id").trim();
            String pid = request.getParameter("pid").trim();
            ProjectInfo project = projectService.getpProjectById(pid);
            if (project.getRecruittype() == EnumTools.RecruitType.社会招聘.ordinal()) {
                String jid = request.getParameter("jid").trim(); // PlanPersondemand实体主键
                SendResumeSZ(project, jid, id, response);

            } else if (project.getRecruittype() == EnumTools.RecruitType.中专校园招聘.ordinal()) {
                if (project.getSeason().equalsIgnoreCase("春季")) {
                    String jid = request.getParameter("jid").trim();
                    SendResumeSZ(project, jid, id, response);
                } else {
                    SendResumeZZ(project, id, response);
                }

            } else if (project.getRecruittype() == EnumTools.RecruitType.高校校园招聘.ordinal()) {
                //String rcode = request.getParameter("rcode").trim(); // 招聘地区编码
                //String region = request.getParameter("region").trim(); // 招聘地区名称
                String jid = request.getParameter("jid").trim(); // PlanPersondemand实体主键
                SendResumeSZ(project, jid, id, response);
                //SendResumeGX(project, rcode, region, id, response);
            } else {
                utilService.printJsonResult(false, "非法访问！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[start] 人工投简历

    //社招投简历
    @SuppressWarnings({"rawtypes", "unchecked"})
    private void SendResumeSZ(ProjectInfo project, String did, String id, HttpServletResponse response) {
        try {
            ProjectInfoJobs demand = projectService.getProjectInfoJob(did);
            if (demand != null) {
                UserResume resume = doResumeService.gUserResume(id);
                //判断简历是否已经创建
                if (resume != null) {
                    //判断是否已经投过简历
                    if (doResumeService.AllowSendResume(project.getId(), resume.getUserid())) {

                        List list = new ArrayList();
                        DUserResume dUserResume = new DUserResume();
                        BeanTools.Copy(resume, dUserResume);
                        String nid = UUID.randomUUID().toString();
                        dUserResume.setId(nid);
                        dUserResume.setAddDate(new Date());
                        dUserResume.setState("未处理");
                        //招聘岗位
                        dUserResume.setJid(demand.getId());
                        dUserResume.setJname(demand.getJobname());
                        //招聘计划
                        dUserResume.setPid("-");
                        dUserResume.setPname("-");

                        //招聘方案
                        dUserResume.setProid(project.getId());
                        dUserResume.setProname(project.getPname());

                        //招聘流程ID
                        String fid = doResumeService.getFirstFlow(project.getId()).getId();
                        dUserResume.setFid(fid);
                        dUserResume.setPath("/" + fid + "/");
                        dUserResume.setFqstate("未放弃");
                        dUserResume.setZlmsg("未发通知");
                        dUserResume.setZsstate("未政审");
                        dUserResume.setTjstate("未体检");
                        dUserResume.setTjmsg("未发通知");
                        dUserResume.setGwstate("未分配");
                        dUserResume.setBdstate("未报到");
                        dUserResume.setBdmsg("未发通知");

                        list.add(dUserResume);

                        String rid = resume.getId();

                        //教育背景
                        List<UserEducation> usereducations = doResumeService.getUserEducation1(rid);
                        for (UserEducation usereducation : usereducations) {
                            DUserEducation dUserEducation = new DUserEducation();
                            BeanTools.Copy(usereducation, dUserEducation);
                            dUserEducation.setId(UUID.randomUUID().toString());
                            dUserEducation.setRid(nid);
                            list.add(dUserEducation);
                        }
                        //工作经验
                        List<UserWorkExperience> userworkexperiences = doResumeService.getUserWorkExperience1(rid);
                        for (UserWorkExperience userworkexperience : userworkexperiences) {
                            DUserWorkExperience dUserWorkExperience = new DUserWorkExperience();
                            BeanTools.Copy(userworkexperience, dUserWorkExperience);
                            dUserWorkExperience.setId(UUID.randomUUID().toString());
                            dUserWorkExperience.setRid(nid);
                            list.add(dUserWorkExperience);
                        }
                        //培训经历
                        List<UserTraining> usertrainings = doResumeService.getUserTraining1(rid);
                        for (UserTraining usertraining : usertrainings) {
                            DUserTraining dUserTraining = new DUserTraining();
                            BeanTools.Copy(usertraining, dUserTraining);
                            dUserTraining.setId(UUID.randomUUID().toString());
                            dUserTraining.setRid(nid);
                            list.add(dUserTraining);
                        }
                        //获奖信息
                        List<UserRewardPunishment> userrewardpunishments = doResumeService.getUserRewardPunishment1(rid);
                        for (UserRewardPunishment userrewardpunishment : userrewardpunishments) {
                            DUserRewardPunishment dUserRewardPunishment = new DUserRewardPunishment();
                            BeanTools.Copy(userrewardpunishment, dUserRewardPunishment);
                            dUserRewardPunishment.setId(UUID.randomUUID().toString());
                            dUserRewardPunishment.setRid(nid);
                            list.add(dUserRewardPunishment);
                        }
                        //家庭成员
                        List<UserFamily> userfamilys = doResumeService.getUserFamily1(rid);
                        for (UserFamily userfamily : userfamilys) {
                            DUserFamily dUserFamily = new DUserFamily();
                            BeanTools.Copy(userfamily, dUserFamily);
                            dUserFamily.setId(UUID.randomUUID().toString());
                            dUserFamily.setRid(nid);
                            list.add(dUserFamily);
                        }

                        utilService.addList(list);
                        utilService.printJsonResult(true, "操作成功！", "no", response);
                    } else {
                        utilService.printJsonResult(false, "请勿重复操作，该用户已投过简历！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "该用户还没有创建简历！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "非法访问！", "no", response);
            }

        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //高校校招投简历
    @SuppressWarnings({"rawtypes", "unchecked"})
    public void SendResumeGX(ProjectInfo project, String rcode, String region, String id, HttpServletResponse response) {
        try {
            UserResume resume = doResumeService.gUserResume(id);
            if (resume == null) {
                utilService.printJsonResult(false, "该用户还没有创建简历！", "no", response);
                return;
            }

            DUserResume dresume = doResumeService.getDResume(resume.getUserid(), project.getId());
            if (dresume != null) {
                utilService.printJsonResult(false, "不能重复投简历！", "no", response);
                return;
            }

            List list = new ArrayList();
            DUserResume dUserResume = new DUserResume();
            BeanTools.Copy(resume, dUserResume);
            String nid = UUID.randomUUID().toString();
            dUserResume.setId(nid);
            dUserResume.setAddDate(new Date());
            dUserResume.setState("未处理");
            //招聘岗位
            dUserResume.setJid("-");
            dUserResume.setJname("-");
            //招聘计划
            dUserResume.setPid("-");
            dUserResume.setPname("-");

            //招聘方案
            dUserResume.setProid(project.getId());
            dUserResume.setProname(project.getPname());

            //招聘流程ID
            String fid = doResumeService.getFirstFlow(project.getId()).getId();
            dUserResume.setFid(fid);
            dUserResume.setPath("/" + fid + "/");
            dUserResume.setFqstate("未放弃");
            dUserResume.setZlmsg("-");
            dUserResume.setZsstate("未政审");
            dUserResume.setTjstate("未体检");
            dUserResume.setTjmsg("未发通知");
            dUserResume.setGwstate("未分配");
            dUserResume.setBdstate("未报到");
            dUserResume.setBdmsg("未发通知");

            //招聘地区
            //dUserResume.setRcode(rcode);
            //dUserResume.setRegion(region);

            list.add(dUserResume);

            String rid = resume.getId();

            //教育背景
            List<UserEducation> usereducations = doResumeService.getUserEducation1(rid);
            for (UserEducation usereducation : usereducations) {
                DUserEducation dUserEducation = new DUserEducation();
                BeanTools.Copy(usereducation, dUserEducation);
                dUserEducation.setId(UUID.randomUUID().toString());
                dUserEducation.setRid(nid);
                list.add(dUserEducation);
            }
            //工作经验
            List<UserWorkExperience> userworkexperiences = doResumeService.getUserWorkExperience1(rid);
            for (UserWorkExperience userworkexperience : userworkexperiences) {
                DUserWorkExperience dUserWorkExperience = new DUserWorkExperience();
                BeanTools.Copy(userworkexperience, dUserWorkExperience);
                dUserWorkExperience.setId(UUID.randomUUID().toString());
                dUserWorkExperience.setRid(nid);
                list.add(dUserWorkExperience);
            }
            //培训经历
            List<UserTraining> usertrainings = doResumeService.getUserTraining1(rid);
            for (UserTraining usertraining : usertrainings) {
                DUserTraining dUserTraining = new DUserTraining();
                BeanTools.Copy(usertraining, dUserTraining);
                dUserTraining.setId(UUID.randomUUID().toString());
                dUserTraining.setRid(nid);
                list.add(dUserTraining);
            }
            //获奖信息
            List<UserRewardPunishment> userrewardpunishments = doResumeService.getUserRewardPunishment1(rid);
            for (UserRewardPunishment userrewardpunishment : userrewardpunishments) {
                DUserRewardPunishment dUserRewardPunishment = new DUserRewardPunishment();
                BeanTools.Copy(userrewardpunishment, dUserRewardPunishment);
                dUserRewardPunishment.setId(UUID.randomUUID().toString());
                dUserRewardPunishment.setRid(nid);
                list.add(dUserRewardPunishment);
            }
            //家庭成员
            List<UserFamily> userfamilys = doResumeService.getUserFamily1(rid);
            for (UserFamily userfamily : userfamilys) {
                DUserFamily dUserFamily = new DUserFamily();
                BeanTools.Copy(userfamily, dUserFamily);
                dUserFamily.setId(UUID.randomUUID().toString());
                dUserFamily.setRid(nid);
                list.add(dUserFamily);
            }

            utilService.addList(list);
            utilService.printJsonResult(true, "操作成功！", "no", response);

        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //中专校招投简历
    @SuppressWarnings({"rawtypes", "unchecked"})
    public void SendResumeZZ(ProjectInfo project, String id, HttpServletResponse response) {
        try {
            UserResume resume = doResumeService.gUserResume(id);
            if (resume == null) {
                utilService.printJsonResult(false, "该用户还没有创建简历！", "no", response);
                return;
            }

            DUserResume dresume = doResumeService.getDResume(resume.getUserid(), project.getId());
            if (dresume != null) {
                utilService.printJsonResult(false, "不能重复投简历！", "no", response);
                return;
            }
            HRZZUser zzuser = doResumeService.getUser(project.getId(), resume.getCardno());
            if (zzuser == null) {
                utilService.printJsonResult(false, "请先导入人员信息！", "no", response);
                return;
            }
            if (zzuser.getState() != EnumTools.zzuserState.已通过.ordinal()) {
                utilService.printJsonResult(false, "个人信息通过才能投递简历！", "no", response);
                return;
            }

            List list = new ArrayList();
            DUserResume dUserResume = new DUserResume();
            BeanTools.Copy(resume, dUserResume);
            String nid = zzuser.getId();
            dUserResume.setId(nid);
            dUserResume.setAddDate(new Date());
            dUserResume.setState("已通过");
            //招聘岗位
            dUserResume.setJid("-");
            dUserResume.setJname("-");
            //招聘计划
            dUserResume.setPid("-");
            dUserResume.setPname("-");

            //招聘方案
            dUserResume.setProid(project.getId());
            dUserResume.setProname(project.getPname());

            //招聘流程ID
            dUserResume.setFid("-");
            dUserResume.setPath("-");
            dUserResume.setFqstate("-");
            dUserResume.setGwstate("未分配");


            list.add(dUserResume);

            String rid = resume.getId();

            //教育背景
            List<UserEducation> usereducations = doResumeService.getUserEducation1(rid);
            for (UserEducation usereducation : usereducations) {
                DUserEducation dUserEducation = new DUserEducation();
                BeanTools.Copy(usereducation, dUserEducation);
                dUserEducation.setId(UUID.randomUUID().toString());
                dUserEducation.setRid(nid);
                list.add(dUserEducation);
            }
            //工作经验
            List<UserWorkExperience> userworkexperiences = doResumeService.getUserWorkExperience1(rid);
            for (UserWorkExperience userworkexperience : userworkexperiences) {
                DUserWorkExperience dUserWorkExperience = new DUserWorkExperience();
                BeanTools.Copy(userworkexperience, dUserWorkExperience);
                dUserWorkExperience.setId(UUID.randomUUID().toString());
                dUserWorkExperience.setRid(nid);
                list.add(dUserWorkExperience);
            }
            //培训经历
            List<UserTraining> usertrainings = doResumeService.getUserTraining1(rid);
            for (UserTraining usertraining : usertrainings) {
                DUserTraining dUserTraining = new DUserTraining();
                BeanTools.Copy(usertraining, dUserTraining);
                dUserTraining.setId(UUID.randomUUID().toString());
                dUserTraining.setRid(nid);
                list.add(dUserTraining);
            }
            //获奖信息
            List<UserRewardPunishment> userrewardpunishments = doResumeService.getUserRewardPunishment1(rid);
            for (UserRewardPunishment userrewardpunishment : userrewardpunishments) {
                DUserRewardPunishment dUserRewardPunishment = new DUserRewardPunishment();
                BeanTools.Copy(userrewardpunishment, dUserRewardPunishment);
                dUserRewardPunishment.setId(UUID.randomUUID().toString());
                dUserRewardPunishment.setRid(nid);
                list.add(dUserRewardPunishment);
            }
            //家庭成员
            List<UserFamily> userfamilys = doResumeService.getUserFamily1(rid);
            for (UserFamily userfamily : userfamilys) {
                DUserFamily dUserFamily = new DUserFamily();
                BeanTools.Copy(userfamily, dUserFamily);
                dUserFamily.setId(UUID.randomUUID().toString());
                dUserFamily.setRid(nid);
                list.add(dUserFamily);
            }

            zzuser.setRstate("已投简历");
            zzuser.setRdate(new Date());
            zzuser.setTel(resume.getTel());

            utilService.editObject(zzuser, list);
            utilService.printJsonResult(true, "操作成功！", "no", response);

        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //社招投简历
    @SuppressWarnings({"rawtypes", "unchecked"})
 /*   private void SendResumeNZ(ProjectInfo project, String did, String id, HttpServletResponse response) {
        try {
            ProjectInfoJobs demand = projectService.getProjectInfoJob(did);
            if (demand != null) {
                UserResume resume = doResumeService.gUserResume(id);
                NZResume nzResume = doResumeService.getNZResume(id);
                //判断简历是否已经创建
                if (resume != null) {
                    //判断是否已经投过简历
                    if (doResumeService.AllowSendResume(project.getId(), resume.getUserid())) {

                        List list = new ArrayList();
                        DNZResume dnzResume = new DNZResume();
                        BeanTools.Copy(resume, dnzResume);
                        String nid = UUID.randomUUID().toString();
                        dnzResume.setId(nid);
                        dnzResume.setAddDate(new Date());
                        dnzResume.setState("未处理");
                        dnzResume.setSexname(resume.getSexname());
                        dnzResume.setUserid(resume.getUserid());
                        dnzResume.setCardno(resume.getCardno());
                        dnzResume.setEducation(resume.getEducation()==null?"-":resume.getEducation());
                        //招聘岗位
                        dnzResume.setJid(demand.getId());
                        dnzResume.setJname(demand.getJobname());
                        //招聘计划
                        dnzResume.setPid("-");
                        dnzResume.setPname("-");
                        //所在部门？？？
                        if(nzResume!=null){
                            dnzResume.setDept1(nzResume.getDept1());
                            dnzResume.setDept2(nzResume.getDept2());
                            dnzResume.setGroupdate(nzResume.getGroupdate());
                            dnzResume.setJob(nzResume.getJob());
                            dnzResume.setRsdate(nzResume.getRsdate());
                            dnzResume.setCode(nzResume.getCode());
                        }else {
                            dnzResume.setDept1("-");
                            dnzResume.setDept2("-");
                            dnzResume.setGroupdate("-");
                            dnzResume.setJob("-");
                            dnzResume.setRsdate("-");
                            dnzResume.setCode("-");
                        }

                        //招聘方案
                        dnzResume.setPlanid(project.getPlanid());
                        dnzResume.setPlanname(project.getPlanname());
                        dnzResume.setPid(project.getId());
                        dnzResume.setPname(project.getPname());

                        //招聘流程ID
                        String fid = doResumeService.getFirstFlow(project.getId()).getId();
                        dnzResume.setFid(fid);
                        dnzResume.setPath("/" + fid + "/");
                        dnzResume.setFqstate("未放弃");
                        dnzResume.setBdstate("未报到");
                        dnzResume.setBdmsg("未发通知");

                        list.add(dnzResume);

                        String rid = resume.getId();

                        //教育背景
                        List<UserEducation> usereducations = doResumeService.getUserEducation1(rid);
                        for (UserEducation usereducation : usereducations) {
                            DUserEducation dUserEducation = new DUserEducation();
                            BeanTools.Copy(usereducation, dUserEducation);
                            dUserEducation.setId(UUID.randomUUID().toString());
                            dUserEducation.setRid(nid);
                            list.add(dUserEducation);
                        }
                        //工作经验
                        List<UserWorkExperience> userworkexperiences = doResumeService.getUserWorkExperience1(rid);
                        for (UserWorkExperience userworkexperience : userworkexperiences) {
                            DNZResumeWork dnzResumeWork = new DNZResumeWork();
                            BeanTools.Copy(userworkexperience, dnzResumeWork);
                            dnzResumeWork.setId(UUID.randomUUID().toString());
                            dnzResumeWork.setRid(nid);
                            dnzResumeWork.setCode(dnzResume.getCode());
                            dnzResumeWork.setCompany(userworkexperience.getCompanyname());
                            dnzResumeWork.setStartdate(userworkexperience.getStarttime());
                            list.add(dnzResumeWork);
                        }
                        //培训经历
                        List<UserTraining> usertrainings = doResumeService.getUserTraining1(rid);
                        for (UserTraining usertraining : usertrainings) {
                            DUserTraining dUserTraining = new DUserTraining();
                            BeanTools.Copy(usertraining, dUserTraining);
                            dUserTraining.setId(UUID.randomUUID().toString());
                            dUserTraining.setRid(nid);
                            list.add(dUserTraining);
                        }
                        //获奖信息
                        List<UserRewardPunishment> userrewardpunishments = doResumeService.getUserRewardPunishment1(rid);
                        for (UserRewardPunishment userrewardpunishment : userrewardpunishments) {
                            DUserRewardPunishment dUserRewardPunishment = new DUserRewardPunishment();
                            BeanTools.Copy(userrewardpunishment, dUserRewardPunishment);
                            dUserRewardPunishment.setId(UUID.randomUUID().toString());
                            dUserRewardPunishment.setRid(nid);
                            list.add(dUserRewardPunishment);
                        }
                        //家庭成员
                        List<UserFamily> userfamilys = doResumeService.getUserFamily1(rid);
                        for (UserFamily userfamily : userfamilys) {
                            DUserFamily dUserFamily = new DUserFamily();
                            BeanTools.Copy(userfamily, dUserFamily);
                            dUserFamily.setId(UUID.randomUUID().toString());
                            dUserFamily.setRid(nid);
                            list.add(dUserFamily);
                        }

                        utilService.addList(list);
                        utilService.printJsonResult(true, "操作成功！", "no", response);
                    } else {
                        utilService.printJsonResult(false, "请勿重复操作，该用户已投过简历！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "该用户还没有创建简历！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "非法访问！", "no", response);
            }

        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }*/

    @Autowired
    private FilePathUtil filePathUtil;

    @ResponseBody
    @RequestMapping(value = "/putCV", method = RequestMethod.POST)
    public ResultBean putCV(HttpServletRequest request, @RequestBody(required = true) MultipartFile file) {
        String type = request.getParameter("type");
        //简历类型
        int resumeTyp;
        switch (type) {
            case "校招":
                resumeTyp = 1;
                break;
            case "社招":
                resumeTyp = 2;
                break;
            default:
                resumeTyp = 1;
                break;
        }
        String mpath = filePathUtil.getMappath();

        ResultBean resultBean = new ResultBean();

        if (file.isEmpty()) {
            resultBean.setState(false);
            resultBean.setMessage("文件为空");
            return resultBean;
        }
        try {
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf('.'));

            //File localTemp = new File(mpath + File.separator + UUID.randomUUID().toString());
            File localTemp = new File(mpath + file.getName());
            file.transferTo(localTemp);

            //try (InputStream inputStream = new FileInputStream(localTemp)) {
            try (InputStream inputStream = new FileInputStream(localTemp)) {
                if (".doc".equalsIgnoreCase(suffix)) {
                    HWPFDocument hwpfDocument = new HWPFDocument(file.getInputStream());

                    //final String[] headPath = {""};
                    String headfilename = System.nanoTime() + ".jpg";
                    Properties pps = new Properties();
                    pps.load(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("FilePath.properties"), "UTF-8"));
                    String headPath = pps.getProperty("headpath");
                    Optional.ofNullable(hwpfDocument.getPicturesTable().getAllPictures().get(0))
                            .ifPresent(picture -> {
                                byte[] bytes = picture.getRawContent();
                                File headfile = new File(headPath + "/" + headfilename);
                                try (OutputStream outputStream = new FileOutputStream(headfile)) {
                                    outputStream.write(bytes);
                                    outputStream.flush();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            });
                    Optional.ofNullable(hwpfExtract(hwpfDocument)).ifPresent(ssm -> {
                        try {
                            save(ssm, resumeTyp, headfilename);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                } else if (".docx".equalsIgnoreCase(suffix)) {
                    XWPFWordExtractor wordExtractor = new XWPFWordExtractor(new XWPFDocument(inputStream));
                    String content = wordExtractor.getText();
                }
            } catch (FileNotFoundException fileNotFoundException) {
                fileNotFoundException.printStackTrace();
            }

            resultBean.setState(true);
            resultBean.setMessage("导入成功");
            return resultBean;
        } catch (Exception exception) {
            exception.printStackTrace();
            resultBean.setState(false);
            resultBean.setMessage("错误");
            return resultBean;
        }
    }

    private void save(Map<String, String> ssm, int resumeType, String head) throws Exception {
        String cardno = "";
        if (ssm != null && ssm.size() > 0) {
            cardno = ssm.get("身份证号");
        } else {
            throw new Exception("获取WORD简历中身份证号异常!");
        }

        boolean isnew = true;
        List deltList = new ArrayList();
        UserResume userResume;
        userResume = resumeService.getUserResumeByCard(cardno);
        if (userResume != null) {
            isnew = false;
            List oldEduactionList = resumeService.getUserEducation(userResume.getId());
            deltList.addAll(oldEduactionList);
            List oldWorkList = resumeService.getUserWorkExperience(userResume.getId());
            deltList.addAll(oldWorkList);
            List oldFamilyList = resumeService.getUserFamily(userResume.getId());
            deltList.addAll(oldFamilyList);
            List oldMajorList = resumeService.getMajors(userResume.getId());
            deltList.addAll(oldMajorList);
            List oldRewardList = resumeService.getUserRewardPunishment(userResume.getId());
            deltList.addAll(oldRewardList);
        } else {
            userResume = new UserResume();
            userResume.setId(UUID.randomUUID().toString());
            userResume.setUserid(UUID.randomUUID().toString());
            String resumeCode = ssm.get("简历编号");
            if (StringTools.trimNotEmpty(resumeCode)) {
                userResume.setCode(ssm.get("简历编号"));
            } else {
                String code = resumeService.CreateResumeCode();
                userResume.setCode(code);
            }

        }
        userResume.setHead(head);
        userResume.setName(ssm.get("姓名"));
        //userResume.setSexname(ssm.get("性别"));
        String sexInfo = ssm.get("性别");
        if (StringTools.trimNotEmpty(sexInfo)) {
            List<BaseData> sexDatas = utilService.getBaseData("A", "0");
            for (BaseData sexData : sexDatas) {
                if (sexInfo.equalsIgnoreCase(sexData.getName())) {
                    userResume.setSexcode(sexData.getCode());
                    userResume.setSexname(sexData.getName());
                    break;
                }
            }
        }

        userResume.setAge(ssm.get("年龄"));
        String mzInfo = ssm.get("民族");
        if (StringTools.trimNotEmpty(mzInfo)) {
            List<BaseData> mzDatas = utilService.getBaseData("B", "0");
            for (BaseData mzData : mzDatas) {
                if (mzInfo.equalsIgnoreCase(mzData.getName())) {
                    userResume.setMzcode(mzData.getCode());
                    userResume.setMzname(mzData.getName());
                    break;
                }
            }
        }

        userResume.setJg(ssm.get("籍贯"));
        userResume.setBirthplace(ssm.get("出生地"));
        String zzmmInfo = ssm.get("政治面貌");
        if (StringTools.trimNotEmpty(zzmmInfo)) {
            List<BaseData> zzmmDatas = utilService.getBaseData("E", "0");
            for (BaseData zzmmData : zzmmDatas) {
                if (zzmmInfo.equalsIgnoreCase(zzmmData.getName())) {
                    userResume.setZzmmcode(zzmmData.getCode());
                    userResume.setZzmmname(zzmmData.getName());
                    break;
                }
            }
        }

        //userResume.setZzmmname(ssm.get("政治面貌"));
        //userResume.setMname(ssm.get("婚姻状态"));
        String hyInfo = ssm.get("婚姻状态");
        if (StringTools.trimNotEmpty(hyInfo)) {
            List<BaseData> hyDatas = utilService.getBaseData("D", "0");
            for (BaseData hyData : hyDatas) {
                if (hyInfo.equalsIgnoreCase(hyData.getName())) {
                    userResume.setMcode(hyData.getCode());
                    userResume.setMname(hyData.getName());
                    break;
                }
            }
        }

        userResume.setExpectedsalaryamount(ssm.get("期望年收入"));
        userResume.setAttendancetime(ssm.get("到岗日期"));
        userResume.setTel(ssm.get("联系电话"));
        userResume.setWorkexperience(ssm.get("求职状态"));
        userResume.setQq(ssm.get("QQ"));
        userResume.setHeight(Integer.parseInt(ssm.get("身高").trim()));
        userResume.setCardno(ssm.get("身份证号"));
        userResume.setEnglishLevel(ssm.get("外语水平"));
        userResume.setHobby(ssm.get("特长爱好"));
        userResume.setNowaddress(ssm.get("家庭住址"));
        userResume.setMainPerformance(ssm.get("主要业绩"));
        userResume.setIntroduction(ssm.get("荣誉"));
        String qq = ssm.get("QQ");
        if (StringTools.trimNotEmpty(qq)) {
            userResume.setEmail(qq + "@qq.com");
        }

        userResume.setBirthday(IdcardUtil.getBirthDate(ssm.get("身份证号")));
        userResume.setHukouaddress(IdcardUtil.getProvinceByIdCard(ssm.get("身份证号")));
        String workdate = ssm.get("参工时间");
        if (StringTools.trimNotEmpty(workdate)) {
            userResume.setWorkdate(timeFormat.parse(workdate));
        }
        userResume.setHometel(" ");
        userResume.setDistribution(0);
        userResume.setResumeType(resumeType);
        try {
            if (!isnew) {
                utilService.editObject(userResume);
            } else {
                HRUsers hrUsers = createNewHrUser(userResume);
                userResume.setUserid(hrUsers.getId());
                utilService.addObject(userResume);
            }

        } catch (Exception e) {
            throw e;
        }

        saveFamilies(ssm, userResume.getId());
        saveWorkExp(ssm, userResume.getId());
        saveFulltimeEdu(ssm, userResume.getId(), 1);
        saveParttimeEdu(ssm, userResume.getId(), 2);
        saveMajor(ssm, userResume.getId());
        saveRewardPunishment(ssm, userResume.getId());

        if (deltList.size() > 0) {
            utilService.delList(deltList);

        }
    }


    private HRUsers createNewHrUser(UserResume userResume) throws Exception {
        HRUsers users = new HRUsers();

        Date tDate = new Date();

        users.setUcode(userResume.getCardno());
        users.setUname(userResume.getName());
        try {
            Map resultMap = memberService.getResults(0, 20, users);
            Object hrusers = resultMap.get("list");
            if (hrusers != null && ((List<HRUsers>) hrusers).size() > 0) {
                HRUsers hu = ((List<HRUsers>) hrusers).get(0);
                users.setTel(userResume.getTel());
                users.setHasresume(EnumTools.IsOrNot.否.ordinal());
                users.setUstate(EnumTools.State.启用.ordinal());
                users.setAnswerResults(1);
                utilService.editObject(hu);
                users = hu;
            } else {

                users.setId(userResume.getUserid());
                users.setAddtime(tDate);
                users.setUcode(userResume.getCardno());
                users.setUemail(userResume.getEmail());
                users.setUname(userResume.getName());
                String pwd = userResume.getCardno().substring(userResume.getCardno().length() - 6);
                String upwd = StringTools.GetMD5Code(pwd);
                users.setUpwd(upwd);
                users.setTel(userResume.getTel());
                users.setHasresume(EnumTools.IsOrNot.否.ordinal());
                users.setUstate(EnumTools.State.启用.ordinal());
                users.setAnswerResults(1);
                utilService.addObject(users);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return users;
    }

    private void saveFamilies(Map<String, String> ssm, String uid) {
        List<UserFamily> userFamilies = ssm.keySet().stream().filter(key -> "家庭成员".equals(key.split(",")[0]))
                .map(key -> key.split(",")[1]).distinct().map(order -> {
                    UserFamily userFamily = new UserFamily();
                    userFamily.setId(UUID.randomUUID().toString());
                    userFamily.setRid(uid);
                    userFamily.setName(ssm.get(String.format("家庭成员,%s,姓名", order)));
                    userFamily.setRelationship(ssm.get(String.format("家庭成员,%s,称谓", order)));
                    userFamily.setAge(ssm.get(String.format("家庭成员,%s,年龄", order)));
                    userFamily.setWorkunit(ssm.get(String.format("家庭成员,%s,工作单位及职务", order)));
                    return userFamily;
                }).filter(userFamily -> StringUtils.isNotEmpty(userFamily.getName() + userFamily.getRelationship() +
                        userFamily.getAge() + userFamily.getWorkunit())).collect(Collectors.toList());
        try {
            utilService.addList(userFamilies);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveWorkExp(Map<String, String> ssm, String uid) {
        List<UserWorkExperience> workExp = ssm.keySet().stream().filter(key -> "工作经历".equals(key.split(",")[0]))
                .map(key -> key.split(",")[1]).distinct().map(order -> {
                    UserWorkExperience userWorkExperience = new UserWorkExperience();
                    userWorkExperience.setId(UUID.randomUUID().toString());
                    userWorkExperience.setRid(uid);
                    String[] times = ssm.get(String.format("工作经历,%s,时间", order)).split("--");
                    for (int i = 0; i < times.length; i++) {
                        if (times[i].contains("至今")) {
                            times[i] = timeFormat.format(System.currentTimeMillis());
                        }
                    }
                    userWorkExperience.setStarttime(times[0]);
                    userWorkExperience.setEndtime(times[times.length - 1]);
                    userWorkExperience.setCompanyname(ssm.get(String.format("工作经历,%s,工作单位", order)));
                    userWorkExperience.setPosition(ssm.get(String.format("工作经历,%s,工作岗位", order)));
                    userWorkExperience.setDepartment(" ");
                    userWorkExperience.setJobduties(" ");
                    userWorkExperience.setSalary(" ");
                    return userWorkExperience;
                }).filter(exp -> StringUtils.isNotEmpty(exp.getStarttime() + exp.getEndtime() +
                        exp.getCompanyname() + exp.getPosition())).collect(Collectors.toList());
        try {
            utilService.addList(workExp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveMajor(Map<String, String> ssm, String uid) throws ParseException {
        List<UserMajor> majorList = new ArrayList<>();

        //String[] times = ssm.get(String.format("工作经历,%s,时间", order)).split("--");
        String majorString = ssm.get("获得职称或职业资格");
        majorString = majorString.replaceAll("，", ",");

        if (StringTools.trimNotEmpty(majorString)) {
            String[] majors = majorString.split("\r");
            for (int i = 0; i < majors.length; i++) {
                UserMajor userMajor = new UserMajor();
                userMajor.setId(UUID.randomUUID().toString());
                userMajor.setRid(uid);
                if (majors[i].contains(",")) {
                    String[] majorInfo = majors[i].split(",");
                    userMajor.setPostgettime(timeFormat.parse(majorInfo[0]));
                    userMajor.setPostspecialty(majorInfo[1]);
                    majorList.add(userMajor);
                } else if (StringTools.trimNotEmpty(majors[i])) {
                    userMajor.setPostgettime(new Date());
                    userMajor.setPostspecialty(majors[i]);
                    majorList.add(userMajor);
                }
            }
        }
        // userMajor.setPostgettime();
        //userMajor.setPostspecialty();
        try {
            utilService.addList(majorList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveRewardPunishment(Map<String, String> ssm, String uid) throws ParseException {
        List<UserRewardPunishment> rewardPunishmentList = new ArrayList<>();
        String rewardPunishmentString = ssm.get("荣誉");

        rewardPunishmentString = rewardPunishmentString.replaceAll("，", ",");
        if (StringTools.trimNotEmpty(rewardPunishmentString)) {
            String[] rewardPunishments = rewardPunishmentString.split("\r");

            for (int i = 0; i < rewardPunishments.length; i++) {
                if (rewardPunishments[i].contains(",")) {
                    UserRewardPunishment rewardPunishment = new UserRewardPunishment();
                    rewardPunishment.setId(UUID.randomUUID().toString());
                    rewardPunishment.setRid(uid);
                    String[] rewardPunishmentInfo = rewardPunishments[i].split(",");
                    rewardPunishment.setGettime(timeFormat.parse(rewardPunishmentInfo[0]));
                    String tempinfo = rewardPunishmentInfo[1];
                    rewardPunishment.setEnterprise(tempinfo.substring(1, tempinfo.indexOf("颁发的")));
                    rewardPunishment.setName(tempinfo.substring(tempinfo.indexOf("颁发的") + 2, tempinfo.length()));
                    rewardPunishment.setType(1);
                    rewardPunishmentList.add(rewardPunishment);
                }
            }
        }
        try {
            utilService.addList(rewardPunishmentList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static final SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy.MM");

    private void saveFulltimeEdu(Map<String, String> ssm, String uid, int type) {
        List<UserEducation> edu = ssm.keySet().stream().filter(key -> "全日制".equals(key.split(",")[0]))
                .map(key -> key.split(",")[1]).distinct().map(order -> {
                    UserEducation education = new UserEducation();
                    education.setId(UUID.randomUUID().toString());
                    education.setRid(uid);
                    String educationTime = ssm.get(String.format("全日制,%s,时间", order));
                    String[] times = null;
                    if (StringTools.trimNotEmpty(educationTime)) {
                        educationTime = educationTime.trim();
                        if (educationTime.contains("--")) {
                            times = ssm.get(String.format("全日制,%s,时间", order)).split("--");
                        } else if (educationTime.contains("-")) {
                            times = ssm.get(String.format("全日制,%s,时间", order)).split("-");
                        } else if (educationTime.contains(" ")) {
                            times = ssm.get(String.format("全日制,%s,时间", order)).split(" ");
                        }

                        try {
                            education.setStarttime(timeFormat.parse(times[0]));
                            education.setEndtime(timeFormat.parse(times[times.length - 1]));

                        } catch (ParseException parseException) {
                            return null;
                        }
                        try {
                            String smString = ssm.get(String.format("全日制,%s,毕业院校/专业", order));
                            fillSchoolInfo(education, smString);

                            List<BaseData> xlDatas = utilService.getBaseData("F", "0");
                            List<BaseData> xwDatas = utilService.getBaseData("G", "0");
                            String xlxwString = ssm.get(String.format("全日制,%s,学历/学位", order));
                            fillXlxwInfo(education, xlDatas, xwDatas, smString, xlxwString);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        education.setTcode("0001");
                        education.setTname("毕业");
                        education.setType(type);
                        education.setFulltime("全日制");
                        return education;
                    } else {
                        return null;
                    }


                }).filter(Objects::nonNull).filter(education -> StringUtils.isNotEmpty(education.getSchoolname() +
                        education.getDegreename())).collect(Collectors.toList());
        try {
            utilService.addList(edu);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void fillSchoolInfo(UserEducation education, String smString) {
        String schoolname = "无";
        String majorname = "无";
        if (smString.contains("/")) {
            schoolname = smString.substring(0, smString.indexOf("/"));
            education.setSchoolname(schoolname);
            majorname = smString.substring(smString.indexOf("/") + 1, smString.length());
            education.setMajorname(majorname);
        } else if (smString.contains(" ")) {
            schoolname = smString.substring(0, smString.indexOf(" "));
            education.setSchoolname(schoolname);
            majorname = smString.substring(smString.indexOf(" ") + 1);
            education.setMajorname(majorname);
        } else {
            education.setSchoolname(smString);
            education.setMajorname("无");
        }
    }


    private void saveParttimeEdu(Map<String, String> ssm, String uid, int type) {
        List<UserEducation> edu = ssm.keySet().stream().filter(key -> "非全日制".equals(key.split(",")[0]))
                .map(key -> key.split(",")[1]).distinct().map(order -> {
                    UserEducation education = new UserEducation();
                    education.setId(UUID.randomUUID().toString());
                    education.setRid(uid);
                    String educationTime = ssm.get(String.format("非全日制,%s,时间", order));
                    String[] times = null;
                    if (StringTools.trimNotEmpty(educationTime)) {
                        educationTime = educationTime.trim();

                        if (educationTime.contains("--")) {
                            times = ssm.get(String.format("非全日制,%s,时间", order)).split("--");
                        } else if (educationTime.contains("-")) {
                            times = ssm.get(String.format("非全日制,%s,时间", order)).split("-");
                        } else if (educationTime.contains(" ")) {
                            times = ssm.get(String.format("非全日制,%s,时间", order)).split(" ");
                        }
                        try {
                            education.setStarttime(timeFormat.parse(times[0]));
                            education.setEndtime(timeFormat.parse(times[times.length - 1]));
                        } catch (ParseException parseException) {
                            return null;
                        }
                        //education.setSchoolname(ssm.get(String.format("非全日制,%s,毕业院校/专业", order)));
                        education.setTcode("0001");
                        education.setTname("毕业");
                        education.setType(type);
                        //education.setDegreename(ssm.get(String.format("非全日制,%s,学历/学位", order)));
                        education.setFulltime("非全日制");
                        try {
                            List<BaseData> xlDatas = utilService.getBaseData("F", "0");
                            List<BaseData> xwDatas = utilService.getBaseData("G", "0");
                            String smString = ssm.get(String.format("非全日制,%s,毕业院校/专业", order));
                            fillSchoolInfo(education, smString);


                            String xlxwString = ssm.get(String.format("非全日制,%s,学历/学位", order));
                            fillXlxwInfo(education, xlDatas, xwDatas, smString, xlxwString);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return education;
                    } else {
                        return null;
                    }
                }).filter(Objects::nonNull).filter(education -> StringUtils.isNotEmpty(education.getSchoolname() +
                        education.getDegreename())).collect(Collectors.toList());
        try {
            utilService.addList(edu);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void fillXlxwInfo(UserEducation education, List<BaseData> xlDatas, List<BaseData> xwDatas, String smString, String xlxwString) {
        if (xlxwString.contains("/")) {
            String educationname = xlxwString.substring(0, xlxwString.indexOf("/"));
            String degreename = xlxwString.substring(xlxwString.indexOf("/") + 1, xlxwString.length());
            fillEducation(education, xlDatas, xwDatas, educationname, degreename);
        } else if (xlxwString.contains(" ")) {
            String educationname = xlxwString.substring(0, xlxwString.indexOf(" "));
            String degreename = xlxwString.substring(xlxwString.indexOf(" ") + 1, xlxwString.length());
            fillEducation(education, xlDatas, xwDatas, educationname, degreename);
        } else {
            education.setSchoolname(smString);
            education.setMajorname("无");
        }
    }

    private void fillEducation(UserEducation education, List<BaseData> xlDatas, List<BaseData> xwDatas, String educationname, String degreename) {
        for (BaseData xldata : xlDatas) {
            if (educationname.contains(xldata.getName())) {
                education.setEducationcode(xldata.getCode());
                education.setEducationname(xldata.getName());
                break;
            }
        }
        if (!educationname.contains("专科")) {
            for (BaseData xldata : xwDatas) {
                if (xldata.getName().equals(degreename)) {
                    education.setDegreecode(xldata.getCode());
                    education.setDegreename(xldata.getName());
                    break;
                }
            }
        } else {
            for (BaseData xldata : xwDatas) {
                if (xldata.getName().equals("无")) {
                    education.setDegreecode(xldata.getCode());
                    education.setDegreename(xldata.getName());
                    break;
                }
            }
        }
    }


    private Map<String, String> hwpfExtract(HWPFDocument hwpfDocument) {
        Range range = hwpfDocument.getRange();
        TableIterator iterator = new TableIterator(range);
        if (iterator.hasNext()) {
            Table table = iterator.next();
            Map<String, String> res = new HashMap<>();
            WordInfoUtil simp = new WordInfoUtil(table, res);
            simp.getValue("简历编号", 0, 0, 5);
            simp.getValue("应聘岗位", 0, 1, 5);
            simp.getValue("应聘时间", 0, 2, 5);
            simp.getValue("姓名", 1, 1);
            simp.getValue("性别", 1, 3);
            simp.getValue("年龄", 1, 5);
            simp.getValue("民族", 2, 1);
            simp.getValue("籍贯", 2, 3);
            simp.getValue("出生地", 2, 5);
            simp.getValue("参工时间", 3, 1);
            simp.getValue("政治面貌", 3, 3);
            simp.getValue("婚姻状态", 3, 5);
            simp.getValue("求职状态", 4, 1);
            simp.getValue("期望年收入", 4, 3);
            simp.getValue("到岗日期", 4, 5);
            simp.getValue("联系电话", 5, 1);
            simp.getValue("QQ", 5, 3);
            simp.getValue("身高", 5, 5);
            simp.getValue("身份证号", 6, 1);
            simp.getValue("外语水平", 6, 3);
            simp.getValue("特长爱好", 7, 1);
            simp.getValue("家庭住址", 7, 3);
            simp.getValue("获得职称或职业资格", 8, 1);

            for (int i = 0; i < 2; i++) {
                simp.getValue(String.format("全日制,%d,时间", i), 10 + i, 1);
                simp.getValue(String.format("全日制,%d,毕业院校/专业", i), 10 + i, 2);
                simp.getValue(String.format("全日制,%d,学历/学位", i), 10 + i, 3);
            }

            for (int i = 0; i < 2; i++) {
                simp.getValue(String.format("非全日制,%d,时间", i), 13 + i, 1);
                simp.getValue(String.format("非全日制,%d,毕业院校/专业", i), 13 + i, 2);
                simp.getValue(String.format("非全日制,%d,学历/学位", i), 13 + i, 3);
            }

            for (int i = 0; i < 6; i++) {
                simp.getValue(String.format("工作经历,%d,时间", i), 16 + i, 1);
                simp.getValue(String.format("工作经历,%d,工作单位", i), 16 + i, 2);
                simp.getValue(String.format("工作经历,%d,工作岗位", i), 16 + i, 3);
            }

            simp.getValue("主要业绩", 22, 1);
            simp.getValue("荣誉", 23, 1);

            for (int i = 0; i < 4; i++) {
                simp.getValue(String.format("家庭成员,%d,称谓", i), 25 + i, 1);
                simp.getValue(String.format("家庭成员,%d,姓名", i), 25 + i, 2);
                simp.getValue(String.format("家庭成员,%d,年龄", i), 25 + i, 3);
                simp.getValue(String.format("家庭成员,%d,政治面貌", i), 25 + i, 4);
                simp.getValue(String.format("家庭成员,%d,工作单位及职务", i), 25 + i, 5);
            }

            return res;
        }
        return null;
    }

    private static class WordInfoUtil {
        public Table table;
        public Map<String, String> res;

        public WordInfoUtil(Table table, Map<String, String> res) {
            this.table = table;
            this.res = res;
        }

        public void getValue(String key, int row, int col) {
            int numParagraph = table.getRow(row).getCell(col).numParagraphs();
            String info = "";
            if (numParagraph > 1) {
                for (int i = 0; i < numParagraph; i++) {
                    info += table.getRow(row).getCell(col).getParagraph(i).text().trim() + "\r";
                }
            } else {
                res.put(key, table.getRow(row).getCell(col).getParagraph(0).text().trim());
            }
            info = StringTools.full2Half(info);
            res.put(key, info);
        }

        public void getValue(String key, int row, int col, int from) {
            //System.out.println(table.getRow(row).getCell(col).text().trim());
            String info = table.getRow(row).getCell(col).getParagraph(0).text().trim().substring(from);
            info = StringTools.full2Half(info);
            res.put(key, info);
        }
    }

    //[end]

    //[end]


    //region [start] 获得招聘方案列表
    /*@RequestMapping("/getproject")
    public void getProjects(HttpServletRequest request,HttpServletResponse response){
        try {
            String planid = request.getParameter("planid").trim();
            List<ProjectInfo> projects = projectService.getProjectByPlan(planid,EnumTools.RecruitType.内部招聘.ordinal());
            StringBuilder pros = new StringBuilder();
            for (ProjectInfo project : projects) {
                if(project.getState()!=EnumTools.ProjectState.编辑中.ordinal())
                    pros.append("<option value='"+project.getId()+"' hrtype='"+project.getRecruittype()+"'>"+project.getPname()+"</option>");
            }
            utilService.printTextResult(pros.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("", response);
        }
    }*/
    //endregion [end]


    //region [start] 获得招聘方案列表(除内招)
    @RequestMapping("/getproject")
    public void getProjects(HttpServletRequest request, HttpServletResponse response) {
        try {
            String addYear = request.getParameter("year").trim();
            if (addYear != null && !addYear.equalsIgnoreCase("")) {
                List<ProjectInfo> projects = projectService.getProjectByYear(addYear);
                if (projects != null && projects.size() > 0) {
                    StringBuilder pros = new StringBuilder();
                    for (ProjectInfo project : projects) {
                        if (project.getState() != EnumTools.ProjectState.编辑中.ordinal()) {
                            pros.append("<option value='" + project.getId() + "' hrtype='" + project.getRecruittype() + "'>" + project.getPname() + "</option>");
                        }
                    }
                    utilService.printTextResult(pros.toString(), response);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("", response);
        }
    }
    //endregion


}

